import "package:flutter/material.dart";
import "package:shared_preferences/shared_preferences.dart";
import "package:word_range_client/widgets/general/PartingLine.dart";

import "../../viewModels/WordBookViewModel.dart";
import "Review.dart";

class Exercise extends StatefulWidget {
  const Exercise({super.key});

  @override
  State<Exercise> createState() => _ExerciseState();
}

class _ExerciseState extends State<Exercise> {
  // 带正确次数统计的单词列表
  List<Map<String, dynamic>> _words = [];
  List<Map<String, dynamic>> _currentList = []; // 当前学习队列
  int _currentIndex = 0;       // 当前单词索引
  int _totalInputCount = 0;    // 总输入次数

  String _targetWord = "error";
  String _targetTranslation = "错误";
  String _example = "";
  String _exampleTranslation = "";
  String _typedWord = "";
  List<Color> _wordColors = [];

  late final TextEditingController _textEditingController;
  final WordBookViewModel _wordBookViewModel = WordBookViewModel();
  bool _isCompletedToday = false; // 新增：标记今天是否已完成学习

  @override
  void initState() {
    _checkCompletionStatus(); // 新增：检查今天是否已完成学习
    _textEditingController = TextEditingController();
    super.initState();
  }

  // 新增：检查今天是否已完成学习
  Future<void> _checkCompletionStatus() async {
    final prefs = await SharedPreferences.getInstance();
    DateTime nowUtc = DateTime.now().toUtc();
    int lastCompletionTime = prefs.getInt("last_learning_completion_time") ?? 0; // 修改键值
    DateTime lastCompletionDate = DateTime.fromMillisecondsSinceEpoch(lastCompletionTime).toUtc();

    // 如果今天已经完成学习，则显示完成对话框
    if (lastCompletionDate.year == nowUtc.year &&
        lastCompletionDate.month == nowUtc.month &&
        lastCompletionDate.day == nowUtc.day) {
      setState(() {
        _isCompletedToday = true;
      });
      _showCompletionDialog();
    } else {
      _fetchWordList();
    }
  }

  // 新增：保存完成学习的时间
  Future<void> _saveCompletionTime() async {
    final prefs = await SharedPreferences.getInstance();
    DateTime nowUtc = DateTime.now().toUtc();
    prefs.setInt("last_learning_completion_time", nowUtc.millisecondsSinceEpoch); // 修改键值
  }

  Future<void> _fetchWordList() async {
    List<Map<String, dynamic>> wordList = await _wordBookViewModel.getRandomNewWordList();
    setState(() {
      _words = wordList.map((e) {
        return {...e, "correctCount": 0};
      }).toList();
      _initCurrentList();
    });
  }

  void _initCurrentList() {
    _currentList = List.from(_words);
    if (_currentList.isNotEmpty) {
      _updateDisplayWord();
    }
  }

  void _updateDisplayWord() {
    setState(() {
      _targetWord = _currentList[_currentIndex]["word"] ?? "error";
      _targetTranslation = _currentList[_currentIndex]["tran"] ?? "错误";
      _example = _currentList[_currentIndex]["example"] ?? "No example available";
      _exampleTranslation = _currentList[_currentIndex]["exampleTran"] ?? "本单词暂无例句";
      _wordColors = List.generate(_targetWord.length, (index) => Colors.grey);
    });
  }

  void _updateTypedWord(String input) {
    setState(() {
      _typedWord = input;
    });

    // 输入完成后处理
    if (input.length == _targetWord.length) {
      bool allCorrect = true;

      // 检查拼写是否正确
      for (int i = 0; i < input.length; i++) {
        if (input[i] != _targetWord[i]) {
          allCorrect = false;
          break;
        }
      }

      // 更新颜色反馈
      setState(() {
        _wordColors = List.generate(_targetWord.length, (index) {
          if (input.length > index) {
            if (input[index] == _targetWord[index]) {
              return Colors.green;
            } else if (_targetWord.contains(input[index])) {
              return Colors.black;
            } else {
              return Theme.of(context).colorScheme.error;
            }
          } else {
            return Colors.grey;
          }
        });
      });

      // 延迟0.8秒后处理
      Future.delayed(const Duration(milliseconds: 800), () {
        setState(() {
          if (allCorrect) {
            _totalInputCount++; // 只有在输入正确时，总输入次数加1
            _currentList[_currentIndex]["correctCount"] += 1;

            if (_currentList[_currentIndex]["correctCount"] >= 3) {
              // 调用 saveOrUpdateReview 方法，将学习情况报告给服务器
              _wordBookViewModel.saveOrUpdateReview(_currentList[_currentIndex]["word"]);
              _currentList.removeAt(_currentIndex);
              if (_currentList.isEmpty) {
                _saveCompletionTime(); // 新增：保存完成学习的时间
                _showCompletionDialog();
                return;
              }
              _currentIndex = _currentIndex >= _currentList.length ? 0 : _currentIndex;
            } else {
              _currentIndex = (_currentIndex + 1) % _currentList.length;
            }
          } else {
            _currentIndex = (_currentIndex + 1) % _currentList.length;
          }

          _updateDisplayWord();
          _clearInput();
        });
      });
    } else {
      // 即使还没输完单词，输入的单词在提示单词中，这个字母也变黑色
      setState(() {
        _wordColors = List.generate(_targetWord.length, (index) {
          if (input.length > index) {
            return Colors.black;
          } else {
            return Colors.grey;
          }
        });
      });
    }
  }

  void _showCompletionDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("完成学习"),
        content: const Text("恭喜！所有单词已通过三次正确拼写！"),
        actions: [
          TextButton(
              onPressed: () {
                Navigator.pop(context); // 关闭对话框
                Navigator.pushReplacement( // 跳转到Review页面
                  context,
                  MaterialPageRoute(builder: (context) => const Review()),
                );
              },
              child: const Text("确定")
          )
        ],
      ),
    );
  }

  void _clearInput() {
    setState(() {
      _textEditingController.clear();
      _wordColors = List.generate(_targetWord.length, (index) => Colors.grey);
    });
  }

  Widget _buildPhoneBody() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          if (_currentList.isEmpty)
            const Text(
              "今天的学习已完成！",
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            )
          else ...[
            const SizedBox(),
            _ProgressIndicator(
              learnedCount: _totalInputCount,
              totalCount: _words.length * 3, // 总次数 = 单词数 * 3
            ),
            Column(
              children: [
                _Word(targetWord: _targetWord, wordColors: _wordColors,),
                _Translation(targetTranslation: _targetTranslation,),
                const SizedBox(height: 5,),
                SizedBox(
                  width: MediaQuery.of(context).size.width * 0.75,
                  child: const PartingLine(),
                ),
                const SizedBox(height: 5,),
                _Example(example: _example,),
                _ExampleTranslation(exampleTranslation: _exampleTranslation,),
                // 用户输入框
                _Input(
                  textEditingController: _textEditingController,
                  updateTypedWord: _updateTypedWord,
                  targetWord: _targetWord,
                ),
              ],
            ),
            const SizedBox(),
            const SizedBox(),
          ],
        ],
      ),
    );
  }

  Widget _buildPadBody() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          if (_currentList.isEmpty)
            const Text(
              "今天的学习已完成！",
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            )
          else ...[
            _ProgressIndicator(
              learnedCount: _totalInputCount,
              totalCount: _words.length * 3, // 总次数 = 单词数 * 3
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                const SizedBox(width: 20,),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _Word(targetWord: _targetWord, wordColors: _wordColors, fontSize: 65.0,),
                    _Translation(targetTranslation: _targetTranslation,),
                  ],
                ),
                const SizedBox(
                  width: 1,
                  height: 100,
                  child: DecoratedBox(
                    decoration: BoxDecoration(color: Colors.grey),
                  ),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    _Example(example: _example, fontSize: 23,),
                    _ExampleTranslation(exampleTranslation: _exampleTranslation, fontSize: 20,),
                  ],
                ),
                const SizedBox(width: 20,),
              ],
            ),
            // 用户输入框
            SizedBox(
              width: 700,
              child: _Input(
                textEditingController: _textEditingController,
                updateTypedWord: _updateTypedWord,
                targetWord: _targetWord,
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildBody() {
    final bool isMobileLayout = MediaQuery.of(context).size.width < 600;
    return isMobileLayout ? _buildPhoneBody() : _buildPadBody();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("单词学习")),
      floatingActionButton: FloatingActionButton(
        onPressed: _clearInput,
        foregroundColor: Theme.of(context).colorScheme.background,
        child: const Icon(Icons.delete_forever),
      ),
      body: _buildBody(),
    );
  }
}

// 修改进度指示器组件
class _ProgressIndicator extends StatelessWidget {
  const _ProgressIndicator({
    required this.learnedCount,
    required this.totalCount,
  });

  final int learnedCount;
  final int totalCount;

  @override
  Widget build(BuildContext context) {
    // 检查分母是否为0，避免Infinity或NaN
    double progress = totalCount == 0 ? 0.0 : learnedCount / totalCount;
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
          child: ClipRRect(
            borderRadius: const BorderRadius.all(Radius.circular(10.0)),
            child: LinearProgressIndicator(
              minHeight: 5, // 增加高度
              backgroundColor: Colors.grey[200], // 更明显的背景色
              color: Theme.of(context).primaryColor, // 使用主题主色
              value: progress, // 使用计算后的进度值
            ),
          ),
        ),
        const SizedBox(height: 5),
        Text(
          '学习进度：${(progress * 100).toStringAsFixed(2)}%',   // 格式化 两位小数
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }
}


class _Word extends StatefulWidget {
  const _Word({super.key, this.targetWord = "Error", required this.wordColors, this.fontSize = 48.0,});

  final String targetWord;
  final List<Color> wordColors;
  final double fontSize;

  @override
  State<_Word> createState() => _WordState();
}

class _WordState extends State<_Word> {
  @override
  Widget build(BuildContext context) {
    // 处理空字符串的情况
    if (widget.targetWord.isEmpty) {
      return const Text(
        "No word to display",
        style: TextStyle(
          color: Colors.grey,
          fontSize: 48.0,
          fontWeight: FontWeight.w600
        ),
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(widget.targetWord.length, (index){
        return Text(
          widget.targetWord[index],
          style: TextStyle(
              color: widget.wordColors[index],
              fontSize: widget.fontSize,
              fontWeight: FontWeight.w600
          ),
        );
      },),
    );
  }
}

class _Translation extends StatefulWidget {
  const _Translation({super.key, this.targetTranslation = "错误"});

  final String targetTranslation;

  @override
  State<_Translation> createState() => _TranslationState();
}

class _TranslationState extends State<_Translation> {
  @override
  Widget build(BuildContext context) {
    return Text(
        widget.targetTranslation,
        style: const TextStyle(
            fontSize: 25.0,
            fontWeight: FontWeight.w500
        )
    );
  }
}

class _Example extends StatefulWidget {
  const _Example({super.key, this.example = "an error has occurred", this.fontSize = 17.0});

  final String example;
  final double fontSize;

  @override
  State<_Example> createState() => _ExampleState();
}

class _ExampleState extends State<_Example> {
  @override
  Widget build(BuildContext context) {
    return Text(
        widget.example,
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: widget.fontSize,
            fontWeight: FontWeight.w400
        )
    );
  }
}

class _ExampleTranslation extends StatefulWidget {
  const _ExampleTranslation({super.key, this.exampleTranslation = "错误示例翻译", this.fontSize = 17.0,});

  final String exampleTranslation;
  final double fontSize;

  @override
  State<_ExampleTranslation> createState() => _ExampleTranslationState();
}

class _ExampleTranslationState extends State<_ExampleTranslation> {
  @override
  Widget build(BuildContext context) {
    return Text(
        widget.exampleTranslation,
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: widget.fontSize,
            fontWeight: FontWeight.w400
        )
    );
  }
}

class _Input extends StatefulWidget {
  const _Input({super.key, required this.textEditingController, required this.updateTypedWord, required this.targetWord});

  final TextEditingController textEditingController;
  final Function(String) updateTypedWord;
  final String targetWord;


  @override
  State<_Input> createState() => _InputState();
}

class _InputState extends State<_Input> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(50, 20, 50, 0),
      child: TextField(
        controller: widget.textEditingController,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.visiblePassword,
        onChanged: widget.updateTypedWord,
        maxLength: widget.targetWord.length,
        decoration: const InputDecoration(
          enabledBorder: OutlineInputBorder(),
          border: OutlineInputBorder(),
          hintText: '请在这里输入',
        ),
      ),
    );
  }
}







